//
//  CarouselView.m
//  itboye_rjy_ios
//
//  Created by pro on 16/1/15.
//  Copyright © 2016年 mc. All rights reserved.
//

#import "ByCoreViewCarousel.h"

#import "ByNetCarouselModel.h"      // 轮播model

@interface ByCoreViewCarousel () <UIScrollViewDelegate>
{
    NSInteger _carouselAmount;
    CGFloat _duration;
}
@property (nonatomic, strong) UIScrollView *scrollView; // 滚动视图
@property (nonatomic, strong) UIPageControl *pageControl; // 分页视图
@property (nonatomic, strong) UIActivityIndicatorView *activity; // 菊花

@property (nonatomic, strong) NSTimer *timer; // 定时器

@end

@implementation ByCoreViewCarousel

- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}

- (instancetype)initWithFrame:(CGRect)frame
                timerDuration:(CGFloat)duration {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
                
        [self _initViews];
        _timer = [NSTimer scheduledTimerWithTimeInterval:duration target:self selector:@selector(_timerAction:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

    }
    
    return self;
}

#pragma mark -- 创建视图 --
- (void)_initViews {
    
    [self _createActivityView]; // 菊花
    [self _createPageControl]; // 分页
}
// 未加载轮播图片时，先显示菊花转动
- (void)_createActivityView {
    
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activity.center = CGPointMake(self.width / 2, self.height / 2);
    _activity.hidesWhenStopped = YES;
    [self addSubview:_activity];
    [_activity startAnimating];
}
// 创建pageView
- (void)_createPageControl {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _pageControl.backgroundColor = [UIColor clearColor];
    _pageControl.currentPageIndicatorTintColor = JM_THEME_COLOR;
    _pageControl.pageIndicatorTintColor = [UIColor colorWithWhite:0.95 alpha:1];
    _pageControl.hidden = YES; // 首先是默认隐藏的
    _pageControl.bottom = self.height - 10;
    _pageControl.center = CGPointMake(SCREEN_WIDTH / 2, _pageControl.center.y);
    [self addSubview:_pageControl];
}
// 创建滚动视图
- (void)_initScrollView {
    
    if (_scrollView) {
        return;
    }
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    _scrollView.contentSize = CGSizeMake(_scrollView.width * (_carouselAmount + 2), _scrollView.height);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    
    // 为了实现轮播，在需要显示的三个视图前后个在放一个（在第一个视图前面方最后一个视图，在最后一个视图后面方第一个视图）
    // 中间主要显示的视图
    for (int i = 0; i < _carouselAmount + 2; i ++) {
        UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(i * _scrollView.width, 0, _scrollView.width, _scrollView.height)];
        view.image = [UIImage imageWithColor:[UIColor lightGrayColor]];
        view.tag = 10 + i;
        [_scrollView addSubview:view];
        view.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_clickViewAtIndex:)];
        [view addGestureRecognizer:tap];
    }
    
    // 显示第一张图片
    _scrollView.contentOffset = CGPointMake(_scrollView.width, 0);
    
    [self insertSubview:_scrollView atIndex:0];
    
}



#pragma mark -- 滑动视图代理 --
// 滑动视图已经停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //如果已经滑动到最后一张，则跳到第二张
    if (_scrollView.contentOffset.x == (_carouselAmount + 1) * _scrollView.width) {
        _scrollView.contentOffset = CGPointMake(_scrollView.width, 0);
    }
    //如果滑动到到第一张，则跳到倒数第二张
    else if (_scrollView.contentOffset.x == 0) {
        _scrollView.contentOffset = CGPointMake(_carouselAmount * _scrollView.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = _scrollView.contentOffset.x / _scrollView.width - 1;
    _pageControl.currentPage = curPage;
}


#pragma mark -- 定时器方法 --
// 定时器方法
- (void)_timerAction:(NSTimer *)timer {
    // 跳转到下一页
    [UIView animateWithDuration:0.5 animations:^{
        _scrollView.contentOffset = CGPointMake(_scrollView.contentOffset.x + _scrollView.width, 0);
    }];
    //如果已经滑动到最后一张，则跳到第二张
    if (_scrollView.contentOffset.x == (_carouselAmount + 1) * _scrollView.width) {
        _scrollView.contentOffset = CGPointMake(_scrollView.width, 0);
    }
    //如果滑动到到第一张，则跳到倒数第二张
    else if (_scrollView.contentOffset.x == 0) {
        _scrollView.contentOffset = CGPointMake(_carouselAmount * _scrollView.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = _scrollView.contentOffset.x / _scrollView.width - 1;
    _pageControl.currentPage = curPage;
}

#pragma mark -- 重写set方法 --
- (void)setModels:(NSArray *)models {

    // 如果没轮播图，则设置一张默认的图片，且不轮播
    if (models == nil || models.count == 0) {
        ByNetCarouselModel *model = [[ByNetCarouselModel alloc] init];
        models = @[model];
    }
    
    NSMutableArray *temp = [NSMutableArray array];
    temp = [models mutableCopy];
    [temp addObject:models[0]];
    [temp insertObject:models[models.count - 1] atIndex:0];
    
    // 设置好轮播数组
    _models = [temp copy];
    
    // 设置轮播数量
    _carouselAmount = models.count;
    
    // 创建滑动视图
    [self _initScrollView];

    // 显示分页视图
    _pageControl.hidden = NO;
    _pageControl.numberOfPages = _carouselAmount;
    
    // 如果只有一张图片，则不轮播
    if (_carouselAmount == 1) {
        _scrollView.scrollEnabled = NO;
        [_timer invalidate];
        _timer = nil;
        _pageControl.hidden = YES;
    }
    
    // 给轮播图片视图设置从网上获取的图片
    for (int tag = 10; tag < 10 + _carouselAmount + 2; tag ++) {
        UIImageView *view = (UIImageView *)[_scrollView viewWithTag:tag];
        ByNetCarouselModel *model = _models[tag - 10];
        NSURL *imgUrl = [NSURL URLWithString:model.img];
        
        [view setImageWithURL:imgUrl placeholderImage:DEFAULT_IMAGE_WIDE completed:nil];
    }
    
    [_activity stopAnimating];


}


- (void)_clickViewAtIndex:(UITapGestureRecognizer *)tap {
    
    NSInteger index = tap.view.tag - 10; // index对应于数据数组中的元素索引
    NSLog(@"对应的轮播轮播:%@", _models[index]);
    
    ByNetCarouselModel *model = _models[index];
    NSString *url = model.url;
    NSLog(@"%@", url);
    if ([url hasPrefix:@"http"]) {
        ByWebViewController *vc = [[ByWebViewController alloc] initWithUrlString:url];
        [self.viewController.navigationController pushViewController:vc animated:YES];
    } 
}
@end
